package com.xiaomage.view.draw12

import android.animation.ValueAnimator
import android.content.Context
import android.graphics.*
import android.view.View
import android.view.animation.LinearInterpolator
import android.graphics.PorterDuff



/**
 * Created by Administrator on 2018/1/8.
 */
class MyView(context: Context):View(context) {
    private lateinit var DSTBitmap:Bitmap;
    private  var SRCBitmap=BitmapFactory.decodeResource(resources,
            R.drawable.text)
    private val paint=getPaint()
    private var dx=0
    private var path=Path()
    init {
        //软件加载
        setLayerType(LAYER_TYPE_SOFTWARE,null)
        DSTBitmap= Bitmap.createBitmap(800,
                800,Bitmap.Config.ARGB_8888)
        //开启动画
        startAnimation()
    }

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        canvas.drawColor(Color.BLACK)

        getPath()
        //canvas.drawPath(path,paint)
        //先清空bitmap上的图像,然后再画上Path
        val c = Canvas(DSTBitmap)
        c.drawColor(Color.BLACK, PorterDuff.Mode.CLEAR)
        c.drawPath(path, paint)
        canvas.drawBitmap(SRCBitmap,0f,0f,paint)

        //保存图层
        val layerId=canvas.saveLayer(0f,0f,width.toFloat(),
                height.toFloat(),paint)
        canvas.drawBitmap(DSTBitmap,0f,0f,paint)
        paint.xfermode = PorterDuffXfermode(PorterDuff.Mode.MULTIPLY)
        canvas.drawBitmap(SRCBitmap,0f,0f,paint)
        paint.xfermode = null
        //还原图层
        canvas.restoreToCount(layerId)
    }
    private fun getPath(){
        path.reset()
        val needY=SRCBitmap.height/2
        path.moveTo((-SRCBitmap.width/2+dx).toFloat(),needY.toFloat())
        var i=-dx
        while (i<2000){
            path.quadTo(i+250f,needY-50f,i+500f,needY.toFloat())
            path.quadTo(i+750f,needY+50f,i+1000f,needY.toFloat())
            i+=1000
        }
        path.lineTo(500f,500f)
        path.lineTo(0f,500f)
        path.close()
    }

    private fun startAnimation(){
        val valueAnimator=ValueAnimator.ofInt(0,SRCBitmap.width/2)
        valueAnimator.duration=2000
        valueAnimator.repeatCount=ValueAnimator.INFINITE
        valueAnimator.repeatMode= ValueAnimator.REVERSE
        valueAnimator.interpolator=LinearInterpolator()
        valueAnimator.addUpdateListener {
            animator->
            dx=animator.animatedValue.toString().toInt()
            postInvalidate()
        }
        valueAnimator.start()
    }
    private fun getPaint():Paint{
        val paint=Paint()
        paint.isAntiAlias=true
        paint.color= Color.GREEN
        paint.style=Paint.Style.FILL_AND_STROKE
        return paint
    }
}